package com.idea.zd.sys.train.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 实现Callable接口实现线程，可以有返回值
 */
public class CallableTest implements Callable<Integer> {
    /**
     * 线程方法体
     * @return
     * @throws Exception
     */
    @Override
    public Integer call() throws Exception {
        int i = 0;

        for (; i<10; i++) {
            System.out.println(Thread.currentThread().getName()+" :"+i);
        }
        return i;
    }

    public static void main(String [] args) throws ExecutionException, InterruptedException {
        CallableTest callableTest = new CallableTest();

        //使用FutureTask来包装Callable对象
        FutureTask<Integer> futureTask = new FutureTask<>(callableTest);

        for(int i =0;i < 100; i++){
            System.out.println(Thread.currentThread().getName()+" :"+i);

            if(i == 20){
                new Thread(futureTask,"有返回值的线程").start();
            }

        }

        //FutureTask的get方法将导制主线程被阻塞
        System.out.println("子线程的返回值"+futureTask.get());

        int s = 5;
        System.out.println(s++);
    }
}
